﻿using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Widget;
using GBU.Services.Common;
using Android.Locations;
using Newtonsoft.Json;

namespace GBU.Services.LocationService
{
    
    [Service]
    [IntentFilter(new string[] { "GpsService" })]
    public class GpsService : Service, ILocationListener
    {
        private const string Tag = "GpsService";

        public override IBinder OnBind(Intent intent)
        {
            return new CommonServiceBinder<GpsService>(this);
        }

        public  LocationManager locationManager;

        long locationInterval = 2000; //gps 获取数据频率 单位MS
        private int minDistance = 1;//gps 最小精度,单位米

        private string locationProvider;


        public override void OnCreate()
        {
            base.OnCreate();
            locationManager = (LocationManager)GetSystemService(Context.LocationService);
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(Tag, "Gps Service Started.");

            return StartCommandResult.NotSticky;
        }

        public void StartGpsListen()
        {
            try
            {
                var locationCriteria = new Criteria { Accuracy = Accuracy.Fine, PowerRequirement = Power.NoRequirement };

                locationProvider = locationManager.GetBestProvider(locationCriteria, true);
                if (!string.IsNullOrEmpty(locationProvider))
                {
                    locationManager.RequestLocationUpdates(locationProvider, locationInterval, minDistance, this);
                }
                else
                {
                    Log.Debug(Tag, "The GPS cannot open.or your device doesn't suppot gps location.");
                    // Toast.MakeText(this, "The GPS cannot open.or your device doesn't suppot gps location.", ToastLength.Short).Show();
                }

                Location location = locationManager.GetLastKnownLocation(locationProvider);

                if (location != null)
                {
                    var initPoint = new LocationData()
                        {
                            Altitude = location.Altitude,
                            Latitude = location.Latitude,
                            Longitude = location.Longitude,
                            Time = location.Time
                        };
                    var msg = string.Format("Init location: latitude:{0}, longitude:{1}", initPoint.Latitude,
                                            initPoint.Longitude);
                    Log.Debug(Tag, msg);
                    var sendData = JsonConvert.SerializeObject(initPoint);
                    SendMessage(sendData);
                }

                //绑定GPS状态监听器
                locationManager.AddGpsStatusListener(new GpsStatusListener(this));
            }
            catch (Exception e)
            {
                Log.Debug(Tag, e.Message);
            }

        }

        public void StopGpsListen()
        {
            locationManager.RemoveUpdates(this);
        }

        void SendMessage(string locationDataJson)
        {
            // Log.Debug(Tag, "The Location Datas: " + locationDataJson);
            if (string.IsNullOrEmpty(locationDataJson))
            {
                Log.Debug(Tag, "The Sending Location Datas is empty");
                return;
            }
            Log.Debug(Tag, "The Sending Location Datas: " + locationDataJson);
            Intent i = new Intent(MessageType.GpsPointing);
            i.PutExtra(MessageType.GpsPointKey, locationDataJson);
            SendBroadcast(i);
        }


        /// <summary>
        /// 设置最小更新位置频率(ms)
        /// </summary>
        /// <param name="interval"></param>
        public void SetLocationInterval(long interval)
        {
            locationInterval = interval;
        }

        /// <summary>
        /// 设置最小经度(两个点之间的距离)(米)
        /// </summary>
        /// <param name="meter"></param>
        public void SetMinimumDistance(int meter)
        {
            minDistance = meter;
        }

        public void OnLocationChanged(Location location)
        {
            //var jingdu = location.Longitude; //经度
            //var weidu = location.Latitude; //纬度
            //var haiba = location.Altitude;//海拔
            //var datetimelong = location.Time;//时间(卫星时间)

            var initPoint = new LocationData()
            {
                Altitude = location.Altitude,
                Latitude = location.Latitude,
                Longitude = location.Longitude,
                Time = location.Time
            };

            var msg = string.Format("the location: latitude:{0}, longitude:{1}", initPoint.Latitude, initPoint.Longitude);
            Log.Debug(Tag, msg);
            SendMessage(JsonConvert.SerializeObject(initPoint));
        }

        public void OnProviderDisabled(string provider)
        {

        }

        public void OnProviderEnabled(string provider)
        {

        }

        public void OnStatusChanged(string provider, Availability status, Bundle extras)
        {
           // var locationProvider=locationManager.GetProvider(provider);
           // locationProvider.
        }
    }
}
